package zheezes.model;

import java.util.ArrayList;
import java.util.List;

import zheezes.util.Visitor;


@SuppressWarnings("unchecked")
public class ObservableTreeNode<T> extends ObservableModel implements
		ITreeNode<T> {
	protected String label;
	protected T data;
	protected ITreeNode parent;
	protected List children = new ArrayList();

	public ObservableTreeNode() {
	}

	public ObservableTreeNode(ITreeNode parent) {
		this.parent = parent;
	}

	public String getLabel() {
		return label;
	}

	public void setLabel(String label) {
		this.label = label;
	}

	public T getData() {
		return data;
	}

	public void setData(T data) {
		this.data = data;
	}

	public ITreeNode getParent() {
		return parent;
	}

	public void setParent(ITreeNode parent) {
		this.parent = parent;
	}

	public List getChildren() {
		return children;
	}

	public void setChildren(List children) {
		this.children.clear();
		this.children.addAll(children);
	}

	public boolean hasChildren() {
		return children.size() != 0;
	}

	public void addChild(ITreeNode child) {
		children.add(child);
	}

	public void removeChild(ITreeNode child) {
		children.remove(child);
	}

	public ITreeNode find(ITreeNode node) {
		if (this == node) {
			return this;
		}
		for (Object o : children) {
			ITreeNode n = (ITreeNode) o;
			ITreeNode r = null;
			if ((r = n.find(node)) != null) {
				return r;
			}
		}
		return null;
	}

	public ITreeNode findByData(Object data) {
		if (this.data == data) {
			return this;
		}
		for (Object o : children) {
			ITreeNode n = (ITreeNode) o;
			ITreeNode r = null;
			if ((r = n.findByData(data)) != null) {
				return r;
			}
		}
		return null;
	}

	public void traverse(Visitor visitor) {
		visitor.visit(data);
		for (Object o : children) {
			ITreeNode node = (ITreeNode) o;
			node.traverse(visitor);
		}
	}
}
